<template>
  <div style="padding:10px;">
    <!-- 查询 -->
    <el-form
      :inline="true"
      class="demo-form-inline"  
      style="margin: 10px 0"
    >
      <el-form-item label="用户名">
        <el-input
          type="text"
          placeholder="请输入用户名"
          v-model="user.username"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input
          type="text"
          placeholder="请输入邮箱"
          v-model="user.email"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input
          type="text"
          placeholder="请输入手机号"
          v-model="user.phone"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getUser()" type="primary">查询</el-button>
        <el-button @click="handleAdd()" type="primary">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 展示 -->
    <el-table
      v-loading="loading"
      border
      stripe
      :data="users"
      style="width: 100%; height: 500px; overflow: auto"
    >
      <el-table-column prop="userId" label="编号" sortable width="70"  align="center"> </el-table-column>
      <el-table-column prop="phone" label="手机" width="100"  align="center"> </el-table-column>
      <el-table-column prop="email" label="邮箱" width="150"  align="center"> </el-table-column>
      <el-table-column prop="username" label="用户名" width="70"  align="center">
      </el-table-column>
       <el-table-column prop="realName" label="真实姓名" width="70"  align="center"></el-table-column>
      <el-table-column prop="password" label="密码" width="180"  align="center">
        ************
      </el-table-column>
      <el-table-column prop="profile" label="交友宣言" width="190"  align="center">
      </el-table-column>
      <el-table-column prop="avatar" label="头像" width="120"  align="center">
        <template v-slot="{ row }">
            <el-image style="width: 80px; height:80px" :src="row.avatar" :preview-src-list="[row.avatar]" />
        </template>
      </el-table-column>
      <el-table-column prop="roleDescribe" label="角色" width="120"  align="center">
        <template v-slot="{ row }">
          <el-button type="success" disabled>{{ row.roleDescribe }}</el-button>
        </template>
      </el-table-column>

      <el-table-column label="操作"  align="center">
        <!-- 通过 Scoped slot 可以获取到 row, column, $index 和 store（table 内部的状态管理）的数据 -->
        <template #default="scope">
          <!-- 编辑 执行的函数 handleEdit,索引和整个数据行"对象"-->
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <!-- 删除的时候 执行的函数 handleDelete -->
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
          <el-button type="primary" @click="handleRole(scope.$index, scope.row)"
            >角色变更</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block" style="margin-top: 20px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[3, 6, 9, 12]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalElements"
      >
      </el-pagination>
    </div>

    <!--修改、新增用户的dialog界面 -->
    <el-dialog :title="title" v-model="dialogFormVisible">
      <el-form :model="updateuser">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="updateuser.username" autocomplete="off"></el-input>
        </el-form-item>
           <el-form-item label="真实姓名" :label-width="formLabelWidth">
          <el-input v-model="updateuser.realName" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item
          label="密&nbsp;&nbsp;&nbsp;&nbsp;码"
          :label-width="formLabelWidth"
        >
          <el-input v-model="updateuser.password" :show-password="true" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="手&nbsp;&nbsp;&nbsp;&nbsp;机"
          :label-width="formLabelWidth"
        >
          <el-input v-model="updateuser.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="邮&nbsp;&nbsp;&nbsp;&nbsp;箱"
          :label-width="formLabelWidth"
        >
          <el-input v-model="updateuser.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="头&nbsp;&nbsp;&nbsp;&nbsp;像"
          :label-width="formLabelWidth"
        >
          <single-upload v-model="imgurl"></single-upload>
          <!-- 预览图片 -->
          <div style="text-align: left; margin-left: 9%">
            <el-image style="width: 100px; height:100px" :src="imgurl" :preview-src-list="[imgurl]" />
          </div>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </div>
    </el-dialog>
    <!--变更角色的dialog界面 -->
    <el-dialog title="角色变更" v-model="dialogFormVisible1" top="30vh">
      <div style="margin-bottom: 30px">
        <el-radio-group v-model="radio" size="large">
          <el-radio-button
            v-for="userrole in userRoles"
            :key="userrole.roleId"
            :label="userrole.roleId"
          >
            {{ userrole.roleDescribe }}
          </el-radio-button>
        </el-radio-group>
      </div>

      <div class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="updateRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SingleUpload from "@/components/upload/singleUpload";
import request from "@/utils/request";

export default {
  name: "UserManage",
  components: { SingleUpload },
  data() {
    return {
      //临时展示的图片
      imgurl: "",
      //用于选择
      radio: "",
      //方便于更新数据
      userId: "",
      //有一个对象 保存了从后端返回的结果，同时这个数据可以和页面的模板语法中变量关联
      //可以实时响应 ,这里数组 [] 和后端返回的 []关联
      users: [], //查询的用户信息
      roleName: "",
      totalElements: 1, //总条数
      currentPage: 1, //当前页
      pageSize: 6, //条数
      pages: 1, //页数
      //这里写了一个对象，包含user对象中的属性
      user: {}, //查询条件用户信息
      dialogFormVisible: false,
      //要修改、新增的user数据，和表单内容相关
      updateuser: {},
      //指定修改、新增标题
      title: "",
      //存储所有角色信息
      userRoles: {},
      formLabelWidth: "120px",
      dialogFormVisible1: false,
    };
  },
  created() {
    this.getUser();
  },
  //自定义函数都可以写在 {}
  methods: {
    //更新角色信息
    updateRole: function () {
      request
        .put("userinfo/changeRole/" + this.userId + "/" + this.radio)
        .then((res) => {
          //请求成功后
          // =>res.data中
          if (res.code === 0) {
            //提示成功
            this.$message({
              showClose: true,
              message: res.msg,
              type: "success",
            });

            //关闭窗口
            this.dialogFormVisible1 = false;
            //重新加载数据
            this.getUser();
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
        })
        .catch((err) => {
          console.log("axios error: " + err);
        });
    },
    //新增
    handleAdd: function () {
      this.title = "新增";
      //清空数据
      this.updateuser = {};
      this.imgurl = "";
      //对话框显示
      this.dialogFormVisible = true;
    },

    //更新和新增
    updateUser: function () {
      this.updateuser.avatar = this.imgurl;
      //调用后端接口，返回数据,要使用axios,post请求
      // axios.put(url,json,{headers:{}}).then()
      //调用后端修改接口
      request
        .put("/userinfo/", JSON.stringify(this.updateuser), {
          //指定header
          headers: {
            //设置请求头
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          //请求成功后
          //这里简化了
          if (res.code === 0) {
            //提示成
            this.$message({
              showClose: true,
              message: res.msg,
              type: "success",
            });

            //关闭窗口
            this.dialogFormVisible = false;
            //重新加载数据
            this.getUser();
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
        })
        .catch((err) => {
          console.log("axios error: " + err);
        });
    },
    //查询
    getUser: function () {
      this.loading=true;//加载
      //调用后端接口，返回数据,要使用axios,post请求
      // axios.post(url,json,{headers:{}}).then()
      request
        .post(
          "/userinfo/page?pageNum=" +
            this.currentPage +
            "&pageSize=" +
            this.pageSize,
          JSON.stringify(this.user)
        )
        .then((res) => {
          //请求成功后
          // =>res.data中
          this.users = res.data.list;
          this.totalElements = res.data.total;
          this.currentPage = res.data.pageNum;
          this.pages = res.data.pages;
          this.roleName = res.data.list.roleDescribe;
          this.loading=false;
        })
        .catch((err) => {
          console.log("axios error: " + err);
        });
    },
    //修改
    handleEdit(index, row) {
      //设置dialogFormVisible 的值为true
      this.title = "修改";
      this.dialogFormVisible = true;
      this.updateuser = row;
      this.imgurl = row.avatar;
    },
    //角色变更
    handleRole(index, row) {
      if (row.roleDescribe === "超级管理员") {
        this.$confirm("该用户是超级管理员不能被变更！！！", "警告", {
          showCancelButton: false,
          type: "error",
        }).catch(() => {
          //你点击了取消
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
      } else {
        this.dialogFormVisible1 = true;
        this.radio = row.roleId;
        this.userId = row.userId;
        request
          .get("/userRole/all")
          .then((res) => {
            //请求成功后
            // =>res.data中
            this.userRoles = res.data;
          })
          .catch((err) => {
            console.log("axios error: " + err);
          });
      }
    },
    //删除
    handleDelete(index, row) {
      console.log(index, row);
      if (row.roleDescribe === "超级管理员") {
        this.$confirm("该用户是超级管理员不能被删除！！！", "警告", {
          showCancelButton: false,
          type: "error",
        }).catch(() => {
          //你点击了取消
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
      } else {
        this.$confirm(
          "此操作将永久删除该" + row.roleDescribe + ", 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          //确定
          .then(() => {
            request.delete("/userinfo/" + row.userId).then((res) => {
              if (res.code === 0) {
                //提示成功
                this.$message({
                  showClose: true,
                  message: "删除成功!",
                  type: "success",
                });
                //重新加载数据
                this.getUser();
              } else {
                this.$message({
                  showClose: true,
                  message: "删除失败!",
                  type: "error",
                });
              }
            });
          })
          .catch(() => {
            //取消
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },
    //改变每页记录数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      //当前用户选择的每页显示几条记录呢
      this.pageSize = val;
      this.currentPage = 1;
      //重新调用
      this.getUser();
    },
    //翻页(点击页码)
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.getUser(); // 获取新的数据
    },
  },
};
</script>
